package cn.cosmosx.base.id;

import cn.cosmosx.base.helper.SpringContextHolder;
import cn.cosmosx.base.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * ID生成器
 */
@Slf4j
@Component
public final class IDGenerator implements InitializingBean {

    /**
     * 生成全局流水号
     */
    public static String generateGlobalSerial() {
        return IDRule.GLOBAL_SERIAL.generate();
    }

    /**
     * 生成资源请求ID
     */
    public static String generateRequestId() {
        return IDRule.REQUEST_ID.generate();
    }

    /**
     * 生成短ID
     */
    public static String generateMiniId() {
        return IDRule.MINI_ID.generate();
    }

    /**
     * 初始化缓存中的流水号
     */
    public static void initialize(RedisService redisService) {
        if (redisService == null) {
            log.error("RedisService bean is null, not initialize IDRules");
            return;
        }
        for (IDRule rule : IDRule.values()) {
            Integer serialSuffix = redisService.get(rule.name());
            rule.getSuffix().set(serialSuffix == null ? 0 : serialSuffix);
            log.info("Initialize {}: {}", rule.name(), rule.getSuffix().get());
        }
    }

    /**
     * 持久化
     */
    public static void persist(RedisService redisService) {
        if (redisService == null) {
            log.error("RedisService bean is null, not persist IDRules");
            return;
        }
        for (IDRule rule : IDRule.values()) {
            redisService.set(rule.name(), rule.getSuffix().get());
            log.info("Persist {}: {}", rule.name(), rule.getSuffix().get());
        }
    }


    @Override
    public void afterPropertiesSet() {
        IDGenerator.initialize(SpringContextHolder.getBean(RedisService.class));
    }

}
